import tkinter as tk
from tkinter import ttk, messagebox


class ListComparatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("志愿四川快速审核工具")
        self.root.geometry("1000x800")

        # 人数统计变量
        self.input_a_count = tk.StringVar(value="当前人数：0")
        self.input_b_count = tk.StringVar(value="当前人数：0")
        self.dup_count = tk.StringVar(value="0 人")
        self.unique_count = tk.StringVar(value="0 人")
        self.error_count = tk.StringVar(value="0 人")

        # 创建主框架
        self.main_frame = ttk.Frame(root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 输入区域
        self.create_input_section()
        # 操作按钮
        self.create_buttons()
        # 结果区域
        self.create_result_section()

    def create_input_section(self):
        """创建输入区域（带人数统计）"""
        input_frame = ttk.Frame(self.main_frame)
        input_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        # A名单输入框
        a_header = ttk.Frame(input_frame)
        ttk.Label(a_header, text="请输入活动名单").pack(side=tk.LEFT)
        ttk.Label(a_header, textvariable=self.input_a_count, foreground="gray").pack(side=tk.LEFT, padx=5)
        a_header.pack()
        self.text_a = tk.Text(input_frame, height=15, width=30)
        self.text_a.pack(fill=tk.BOTH, expand=True)

        # B名单输入框
        b_header = ttk.Frame(input_frame)
        ttk.Label(b_header, text="请输入志愿四川导出名单").pack(side=tk.LEFT)
        ttk.Label(b_header, textvariable=self.input_b_count, foreground="gray").pack(side=tk.LEFT, padx=5)
        b_header.pack(pady=(10, 0))
        self.text_b = tk.Text(input_frame, height=15, width=30)
        self.text_b.pack(fill=tk.BOTH, expand=True)

    def create_buttons(self):
        """创建操作按钮"""
        btn_frame = ttk.Frame(self.main_frame)
        btn_frame.pack(side=tk.LEFT, padx=20)

        ttk.Button(btn_frame, text="开始审核 →", command=self.compare_lists).pack(pady=20)
        ttk.Button(btn_frame, text="清空所有", command=self.clear_all).pack()

    def create_listbox_with_scroll(self, parent, title, count_var):
        """创建带人数统计的列表组件（修复缩进）"""
        frame = ttk.Frame(parent)

        # 标题栏
        header = ttk.Frame(frame)
        ttk.Label(header, text=title, font=('微软雅黑', 10, 'bold')).pack(side=tk.LEFT)
        ttk.Label(header, textvariable=count_var, foreground="blue").pack(side=tk.LEFT, padx=5)
        header.pack()

        # 列表和滚动条
        listbox_frame = ttk.Frame(frame)
        listbox = tk.Listbox(
            listbox_frame,
            height=10,
            width=30,
            exportselection=False,
            selectmode=tk.EXTENDED
        )
        scrollbar = ttk.Scrollbar(listbox_frame, orient="vertical", command=listbox.yview)
        listbox.configure(yscrollcommand=scrollbar.set)

        # 右键菜单
        context_menu = tk.Menu(listbox, tearoff=0)
        context_menu.add_command(label="复制选中", command=lambda: self.copy_selected(listbox))
        context_menu.add_command(label="复制全部", command=lambda: self.copy_all(listbox))
        listbox.bind("<Button-3>", lambda e: context_menu.tk_popup(e.x_root, e.y_root))

        listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        listbox_frame.pack(fill=tk.BOTH, expand=True)

        # 操作按钮
        btn_frame = ttk.Frame(frame)
        ttk.Button(btn_frame, text="↘ 复制全部",
                   command=lambda lb=listbox: self.copy_all(lb)).pack(side=tk.LEFT, padx=2)
        ttk.Button(btn_frame, text="␣ 空格格式",
                   command=lambda lb=listbox: self.copy_space(lb)).pack(side=tk.LEFT, padx=2)
        btn_frame.pack(fill=tk.X, pady=5)

        return frame, listbox

    def create_result_section(self):
        """创建结果展示区域"""
        result_frame = ttk.Frame(self.main_frame)
        result_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=10)

        # 三个结果列表
        self.dup_frame, self.dup_listbox = self.create_listbox_with_scroll(result_frame, "审核通过", self.dup_count)
        self.dup_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        self.unique_frame, self.unique_listbox = self.create_listbox_with_scroll(result_frame, "未报名",
                                                                                 self.unique_count)
        self.unique_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        self.error_frame, self.error_listbox = self.create_listbox_with_scroll(result_frame, "错误报名",
                                                                               self.error_count)
        self.error_frame.pack(fill=tk.BOTH, expand=True, pady=5)

    def parse_text(self, text_widget):
        """处理特殊字符和空值"""
        content = text_widget.get("1.0", tk.END)
        return {
            item.translate(str.maketrans('', '', ' "\''))  # 删除所有空格和引号
            for item in content.replace(',', '\n').split('\n')
            if item.strip()
        }

    def compare_lists(self):
        """执行比较操作（含人数统计）"""
        try:
            # 清空结果
            for listbox in [self.dup_listbox, self.unique_listbox, self.error_listbox]:
                listbox.delete(0, tk.END)

            # 获取数据
            set_a = self.parse_text(self.text_a)
            set_b = self.parse_text(self.text_b)

            # 更新输入人数
            self.input_a_count.set(f"当前人数：{len(set_a)}")
            self.input_b_count.set(f"当前人数：{len(set_b)}")

            if not (set_a or set_b):
                messagebox.showwarning("提示", "请先输入名单内容")
                return

            # 计算各项结果
            duplicates = sorted(set_a & set_b)
            unique_to_a = sorted(set_a - set_b)
            error_registration = sorted(set_b - set_a)

            # 更新结果人数
            self.dup_count.set(f"{len(duplicates)} 人")
            self.unique_count.set(f"{len(unique_to_a)} 人")
            self.error_count.set(f"{len(error_registration)} 人")

            # 填充数据
            for listbox, items in [
                (self.dup_listbox, duplicates),
                (self.unique_listbox, unique_to_a),
                (self.error_listbox, error_registration)
            ]:
                for item in items:
                    listbox.insert(tk.END, item)

        except Exception as e:
            messagebox.showerror("错误", f"请联系QQ：1147469299\n错误详情：{str(e)}")

    def copy_selected(self, listbox):
        """复制选中项"""
        selected = listbox.curselection()
        if selected:
            text = '\n'.join(listbox.get(i) for i in selected)
            self._copy_to_clipboard(text, len(selected))

    def copy_all(self, listbox):
        """复制全部项"""
        items = listbox.get(0, tk.END)
        if items:
            self._copy_to_clipboard('\n'.join(items), len(items))

    def copy_space(self, listbox):
        """复制为空格分隔"""
        items = listbox.get(0, tk.END)
        if items:
            self._copy_to_clipboard(' '.join(items), len(items), "空格分隔")

    def _copy_to_clipboard(self, text, count, format="正常"):
        """通用复制方法"""
        self.root.clipboard_clear()
        self.root.clipboard_append(text)
        messagebox.showinfo("复制成功",
                            f"已复制 {count} 条数据\n格式：{format}\n内容已存入剪贴板")

    def clear_all(self):
        """清空所有内容"""
        for widget in [self.text_a, self.text_b]:
            widget.delete("1.0", tk.END)
        for listbox in [self.dup_listbox, self.unique_listbox, self.error_listbox]:
            listbox.delete(0, tk.END)
        self.input_a_count.set("当前人数：0")
        self.input_b_count.set("当前人数：0")
        self.dup_count.set("0 人")
        self.unique_count.set("0 人")
        self.error_count.set("0 人")


if __name__ == "__main__":
    root = tk.Tk()
    app = ListComparatorApp(root)
    root.mainloop()